package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.common.MenuItem;
	import example.documentbased.editorModule.common.MenuItemTypes;
	import example.documentbased.editorModule.models.EditorModuleModel;
	
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class ApplyMenyItemCommand extends ReactiveCommand
	{
		private var _editorModel:EditorModuleModel;
		private var _menuItem:MenuItem;
		private var _editorController:IEditorController;
		
		public function ApplyMenyItemCommand(editorModel:EditorModuleModel,
											 editorController:IEditorController)
		{
			_editorModel = editorModel;
			_editorController = editorController;
		}
		
		public function initialize(menuItem:MenuItem):IReactiveCommand
		{
			_menuItem = menuItem;
			markAsInitialized();
			
			return this;
		}
		
		override public function observable():IObservable
		{
			var command:IReactiveCommand;
			
			switch(_menuItem.type)
			{
				case MenuItemTypes.CREATE:
				{
					command = _editorController.getCreateDocumentCommand();
					break;
				}
				case MenuItemTypes.OPEN:
				{
					command = _editorController.getSelectDocumentCommand();
					break;
				}
				case MenuItemTypes.CLOSE:
				{
					command = _editorController.withContext(new RefreshContext())
						.getCloseDocumentCommand(_editorModel.currentDocument);
					break;
				}
				case MenuItemTypes.CLOSE_ALL:
				{
					command = _editorController.getCloseAllDocumentsCommand();
					break;
				}
				case MenuItemTypes.SAVE:
				{
					if	(_editorModel.currentDocument.id)
					{
						command = _editorController.withContext(new RefreshContext())
							.getSaveDocumentCommand(_editorModel.currentDocument);
					}
					else
					{
						command = _editorController.withContext(new RefreshContext())
							.getSaveAsDocumentCommand(_editorModel.currentDocument);
					}
					break;
				}
				case MenuItemTypes.SAVE_AS:
				{
					command = _editorController.withContext(new RefreshContext())
						.getSaveAsDocumentCommand(_editorModel.currentDocument);
					break;
				}
				case MenuItemTypes.SAVE_ALL:
				{
					command = _editorController.getSaveAllDocumentsCommand();
					break;
				}
				case MenuItemTypes.DELETE:
				{
					command = _editorController.getDeleteDocumentCommand(_editorModel.currentDocument);
					break;
				}
			}
			
			return command ? command.observable() : 
				Observable.value(new Unit());
		}
	}
}